from django.contrib.auth import get_user_model
from django.shortcuts import render, get_object_or_404
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status, viewsets
from rest_framework.authtoken.models import Token
from django.contrib.auth.hashers import make_password, check_password
from rest_framework.settings import api_settings

from .models import (
    Notice, Active, BgPic, Bill, Comment,
    Enotice, LostFound, User, Property,
    Repair, Staff, SearchRecord, ActivityRegistration, PropertyUserRelation
)
from .serializers import (
    NoticeSerializer, ActiveSerializer, BgPicSerializer,
    BillSerializer, CommentSerializer, EnoticeSerializer,
    LostFoundSerializer, UserSerializer, PropertySerializer,
    RepairSerializer, StaffSerializer, SearchRecordSerializer, ActivityRegistrationSerializer,
    PropertyUserRelationSerializer
)


# Notice API
@api_view(['GET', 'POST'])
def notice_list_create(request):
    """
    获取所有通知或创建新通知
    """
    if request.method == 'GET':
        notices = Notice.objects.all().order_by('-createdAt')
        serializer = NoticeSerializer(notices, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = NoticeSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PUT', 'DELETE'])
def notice_detail(request, pk):
    """
    获取、更新或删除单个通知
    """
    notice = get_object_or_404(Notice, pk=pk)
    if request.method == 'GET':
        serializer = NoticeSerializer(notice)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = NoticeSerializer(notice, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        notice.delete()
        return Response(status=status.HTTP_200_OK)


# Active API
@api_view(['GET', 'POST'])
def active_list(request):
    """
    获取所有活动或创建新活动
    """
    if request.method == 'GET':
        # 从认证的用户获取user_id，如果未登录则为0
        user_id = request.user.id if request.user.is_authenticated else 0
        
        # 获取搜索关键词，如果没有则为空
        keyword = request.query_params.get('keyword', '')
        category = request.query_params.get('category', '')
        # 创建搜索记录
        if keyword and user_id!=0:  # 只有在有搜索关键词时才创建记录
            SearchRecord.objects.create(
                userId=user_id,
                searchKeyword=keyword
            )
        actives = Active.objects.all().order_by('-id')
        if category:
            actives = actives.filter(category=category)
        if keyword:
            actives = actives.filter(title__icontains=keyword)
        serializer = ActiveSerializer(actives, many=True)
        
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ActiveSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PUT', 'DELETE'])
def active_detail(request, pk):
    """
    获取、更新或删除单个活动
    """
    try:
        active = Active.objects.get(pk=pk)
    except Active.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        # 浏览次数加1
        active.browseCount += 1
        active.save()
        serializer = ActiveSerializer(active)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = ActiveSerializer(active, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        active.delete()
        return Response(status=status.HTTP_200_OK)
    return None


@api_view(['GET'])
def active_by_category(request, category):
    """
    按分类获取活动
    """
    actives = Active.objects.filter(category=category).order_by('-id')
    serializer = ActiveSerializer(actives, many=True)
    return Response(serializer.data)






@api_view(['GET'])
def active_by_user(request, user_id):
    """
    按用户ID获取活动
    """
    actives = Active.objects.filter(user_id=user_id).order_by('-id')
    serializer = ActiveSerializer(actives, many=True)
    return Response(serializer.data)


# BgPic API
@api_view(['GET','POST'])
def bgpic_list(request):
    """
    获取所有背景图片
    """
    if request.method == 'GET':
        bgpics = BgPic.objects.all()
        serializer = BgPicSerializer(bgpics, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = BgPicSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def bgpic_detail(request, pk):
    """
    删改查
    """
    try:
        bgpic = BgPic.objects.get(pk=pk)
    except BgPic.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    if request.method == 'GET':
        serializer = BgPicSerializer(bgpic)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = BgPicSerializer(bgpic, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        bgpic.delete()
        return Response(status=status.HTTP_200_OK)



class BillViewSet(viewsets.ModelViewSet):
    queryset = Bill.objects.all().order_by('-billtime')
    serializer_class = BillSerializer




@api_view(['GET'])
def bill_by_user(request, user_id):
    """
    获取指定用户的所有账单
    """
    bills = Bill.objects.filter(userId=user_id).order_by('-billtime')
    serializer = BillSerializer(bills, many=True)
    return Response(serializer.data)



# Comment API
@api_view(['GET', 'POST'])
def comment_list(request):
    """
    获取所有评论或创建新评论
    """
    if request.method == 'GET':
        comments = Comment.objects.all().order_by('-id')
        serializer = CommentSerializer(comments, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = CommentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'PUT', 'DELETE'])
def comment_detail(request, pk):

    try:
        comment = Comment.objects.get(pk=pk)
    except Comment.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    if request.method == 'GET':
        serializer = CommentSerializer(comment)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = CommentSerializer(comment, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        comment.delete()
        return Response(status=status.HTTP_200_OK)
    return None


# Enotice API
@api_view(['GET', 'POST'])
def enotice_list(request):
    """
    获取所有紧急通知或创建新紧急通知
    """
    if request.method == 'GET':
        enotices = Enotice.objects.all().order_by('-time')
        serializer = EnoticeSerializer(enotices, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = EnoticeSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PUT', 'DELETE'])
def enotice_detail(request, pk):
    """
    获取、更新或删除单个紧急通知
    """
    try:
        enotice = Enotice.objects.get(pk=pk)
    except Enotice.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = EnoticeSerializer(enotice)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = EnoticeSerializer(enotice, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        enotice.delete()
        return Response(status=status.HTTP_200_OK)


# LostFound API
@api_view(['GET', 'POST'])
def lostfound_list(request):
    """
    获取所有失物招领或创建新失物招领
    """
    if request.method == 'GET':
        category = request.GET.get('category')
        name = request.GET.get('name')

        queryset = LostFound.objects.all().order_by('-time')
        if category:
            queryset = queryset.filter(category=category)
        if name:
            queryset = queryset.filter(name__icontains=name)

        serializer = LostFoundSerializer(queryset, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = LostFoundSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


    return Response( status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PUT', 'DELETE'])
def lostfound_detail(request, pk):
    """
    获取、更新或删除单个失物招领
    """
    try:
        lostfound = LostFound.objects.get(pk=pk)
    except LostFound.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = LostFoundSerializer(lostfound)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = LostFoundSerializer(lostfound, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        lostfound.delete()
        return Response(status=status.HTTP_200_OK)

    return Response(status=status.HTTP_400_BAD_REQUEST)





# User API
@api_view(['GET', 'POST'])
def user_list(request):
    """
    获取所有用户或创建新用户
    """
    if request.method == 'GET':
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        data = request.data.copy()
        # 对密码进行哈希处理
        if 'password' in data:
            data['password'] = make_password(data['password'])

        serializer = UserSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PUT', 'DELETE'])
def user_detail(request, pk):
    """
    获取、更新或删除单个用户
    """
    try:
        user = User.objects.get(id=pk)
    except User.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = UserSerializer(user)
        return Response(serializer.data)

    elif request.method == 'PUT':
        data = request.data.copy()
        # 对密码进行哈希处理
        if 'password' in data and data['password'] != user.password:
            data['password'] = make_password(data['password'])

        serializer = UserSerializer(user, data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        user.delete()
        return Response(status=status.HTTP_200_OK)



class PropertyViewSet(viewsets.ModelViewSet):
    queryset = Property.objects.all().order_by("-id")
    serializer_class = PropertySerializer


@api_view(['GET'])
def property_by_user(request, user_id):
    """
    获取指定用户的所有房产
    """
    properties = Property.objects.filter(userId=user_id)
    serializer = PropertySerializer(properties, many=True)
    return Response(serializer.data)


@api_view(['GET'])
def repair_by_user(request, user_id):
    """
    获取指定用户的所有报修
    """
    repairs = Repair.objects.filter(userId=user_id).order_by('-time')
    serializer = RepairSerializer(repairs, many=True)
    return Response(serializer.data)

class RepairViewSet(viewsets.ModelViewSet):
    queryset = Repair.objects.all().order_by('-time')
    serializer_class = RepairSerializer

# 登录接口
class CustomAuthToken(ObtainAuthToken):
    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({
            'token': token.key,
            'userId': user.id,
            'username': user.username,
            'email': user.email,
            'tel': user.tel,
            'avatar': user.avatar,
        }, status=status.HTTP_200_OK)

@api_view(['GET'])
def search_record_by_user(request, user_id):
    """
    获取指定用户的所有搜索记录
    """
    search_records = SearchRecord.objects.filter(userId=user_id).order_by('-id')
    serializer = SearchRecordSerializer(search_records, many=True)
    return Response(serializer.data)

@api_view(['GET', 'POST'])
def activity_registration_list(request):
    """
    获取所有报名记录或创建新报名
    """
    if request.method == 'GET':
        registrations = ActivityRegistration.objects.all()
        serializer = ActivityRegistrationSerializer(registrations, many=True)
        return Response(serializer.data)
    
    elif request.method == 'POST':
        # 检查是否已经报名
        existing_registration = ActivityRegistration.objects.filter(
            userId=request.data.get('userId'),
            activityId=request.data.get('activityId')
        ).first()
        
        if existing_registration:
            return Response(
                {'detail': '您已经报名过这个活动了'},
                status=status.HTTP_400_BAD_REQUEST
            )
            
        serializer = ActivityRegistrationSerializer(data=request.data)
        if serializer.is_valid():
            registration = serializer.save()
            # 更新活动的参与人数
            activity = registration.activityId
            activity.participater += 1
            activity.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    return None


@api_view(['GET', 'PUT', 'DELETE'])
def activity_registration_detail(request, pk):
    """
    获取、更新或删除单个报名记录
    """
    try:
        registration = ActivityRegistration.objects.get(pk=pk)
    except ActivityRegistration.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = ActivityRegistrationSerializer(registration)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = ActivityRegistrationSerializer(registration, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        # 更新活动的参与人数
        activity = registration.activityId
        activity.participater = max(0, activity.participater - 1)  # 确保不会小于0
        activity.save()
        registration.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

@api_view(['GET'])
def user_registrations(request, user_id):
    """
    获取用户的所有报名记录
    """
    registrations = ActivityRegistration.objects.filter(userId=user_id)
    serializer = ActivityRegistrationSerializer(registrations, many=True)
    return Response(serializer.data)

@api_view(['GET'])
def activity_registrations(request, activity_id):
    """
    获取活动的所有报名记录
    """
    registrations = ActivityRegistration.objects.filter(activityId=activity_id)
    serializer = ActivityRegistrationSerializer(registrations, many=True)
    return Response(serializer.data)

class UserRelationViewSet(viewsets.ModelViewSet):
    queryset = PropertyUserRelation.objects.all()
    serializer_class = PropertyUserRelationSerializer

@api_view(['GET'])
def user_relations(request, user_id):
    """
    获取指定用户的所有物业关系记录
    """
    relations = PropertyUserRelation.objects.filter(userId=user_id).select_related('staffId')
    serializer = PropertyUserRelationSerializer(relations, many=True)
    return Response(serializer.data)

class StaffViewSet(viewsets.ModelViewSet):
    queryset = Staff.objects.all()
    serializer_class = StaffSerializer

# 退出登录
@api_view(['POST'])
def logout(request):
    """
    用户退出登录
    """
    # 获取用户令牌
    token = request.data.get('token')

    # 删除令牌
    try:
        token_obj = Token.objects.get(key=token)
        token_obj.delete()
        return Response({'message': '退出登录成功'}, status=status.HTTP_200_OK)
    except Token.DoesNotExist:
        return Response({'message': '用户未登录'}, status=status.HTTP_400_BAD_REQUEST)

#获取某个活动所有评论
@api_view(['GET'])
def active_comments(request):
    if request.method == 'GET':
        active_id = request.GET.get('active_id')
        comments = Comment.objects.filter(activesId=active_id)
        serializer = CommentSerializer(comments, many=True)
        return Response(serializer.data)
    return None